package com.neusoft.neuiotms.common.repository.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.neusoft.bizcore.web.jpa.repository.AbstractRepository;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.neuiotms.common.model.QSysTask;
import com.neusoft.neuiotms.common.model.SysTask;
import com.neusoft.neuiotms.common.model.enums.SysTaskStatus;
import com.neusoft.neuiotms.common.repository.CustomizedSysTaskRepository;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;

public class CustomizedSysTaskRepositoryImpl extends AbstractRepository implements CustomizedSysTaskRepository {

    @Override
    public Page<SysTask> search(final Pageable pageable, final Searchable searchable) {
        final QSysTask qSysTask = QSysTask.sysTask;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<SysTask> query = this.query().selectFrom(qSysTask);
        query.where(where);
        return super.search(query, pageable);
    }

    @Override
    protected Class<?> getModelClass() {
        return SysTask.class;
    }

    private BooleanBuilder buildWhere(final Searchable searchable) {
        final BooleanBuilder where = new BooleanBuilder();
        final QSysTask qSysTask = QSysTask.sysTask;

        if (!StringUtils.isEmpty(searchable.getStrValue("name"))) {
            where.and(super.containsStr(qSysTask.name, searchable, "name"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("status"))) {
            where.and(
                    super.equalsEnum(qSysTask.status, searchable, "status", value -> SysTaskStatus.valueOf(value)));
        }

        return where;
    }
}
